/**
 * 流处理工具
 * @author lms 2021.03.26
 */
package ms.core.tool;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;

public class StreamTool {

	public static InputStream loadFileToStream(Class<?> cls, String fileName) {
		try {
			File file = new File(fileName);
			if (file.exists()) {
				return new FileInputStream(file);
			}

			String fullName = System.getProperty("user.dir")+fileName;
			file = new File(fullName);
			if (file.exists()) {
				return new FileInputStream(file);
			}
			
			fullName = System.getProperty("user.dir")+"/src/main/resources/"+fileName;
			file = new File(fullName);
			if (file.exists()) {
				return new FileInputStream(file);
			}
			
			return cls.getResourceAsStream(fileName);
		} catch(Exception e) {
			Log4j2Tool.error(StreamTool.class, e);
			return null;
		}
	}

	public static OutputStream getOutputStream(String fileName) {
		try {
			File file = new File(fileName);
			if (file.exists()) {
				return new FileOutputStream(file);
			}

			String fullName = System.getProperty("user.dir")+fileName;
			file = new File(fullName);
			if (file.exists()) {
				return new FileOutputStream(file);
			}
			
			fullName = System.getProperty("user.dir")+"/src/main/resources/"+fileName;
			file = new File(fullName);
			if (file.exists()) {
				return new FileOutputStream(file);
			}
		} catch(Exception e) {
			Log4j2Tool.error(StreamTool.class, e);
		}
		return null;
	}
	
	/**
	 * 关闭reader
	 * @param reader
	 */
	public static void closeReader(Reader reader) {
		try {
			if (reader!=null) reader.close();
		} catch(Exception e) {
			Log4j2Tool.error(StreamTool.class, "closeReader:", e);
		}
	}

	/**
	 * 关闭输入流
	 * @param reader
	 */
	public static void closeInputStream(InputStream is) {
		try {
			if (is!=null) is.close();
		} catch(Exception e) {
			Log4j2Tool.error(StreamTool.class, "closeInputStream:", e);
		}
	}

	/**
	 * 关闭输出流
	 * @param reader
	 */
	public static void closeOutputStream(OutputStream os) {
		try {
			if (os!=null) os.close();
		} catch(Exception e) {
			Log4j2Tool.error(StreamTool.class, "closeOutputStream:", e);
		}
	}

	/**
	 * inputStream 流转 String
	 * @param is InputStream 对象
	 * @param charset 字符集名称
	 * @return
	 */
	public static String inputStreamToString(InputStream is, String charset) {
		String ret = null;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		try {
			int len;
			byte[] buf = new byte[2048];
			while ((len=is.read(buf))!=-1) {
				baos.write(buf, 0, len);
			}
			if (StrTool.isBlank(charset))
				ret = baos.toString();
			else
				ret = baos.toString(charset);
		}catch(Exception e) {
			Log4j2Tool.error(StreamTool.class, "inputStreamToString:", e);
		}

		closeOutputStream(baos);
		return ret;
	}
}
